package testSDS;

public class MySDS {

    private int len;

    private int free;

    private char [] buf;

    public MySDS() {
        buf = new char[16];
        free = 16;
    }

    public MySDS(String str) throws Exception {
        buf = new char[str.length() * 2 + 1];
        len = 0;
        strcat(str);
    }

    public int getLen() {
        return len;
    }


    public int getFree() {
        return free;
    }

    public char[] getBuf() {
        return buf;
    }

    public void strcat(String str) throws Exception{
        if (str == null || str.length() == 0) {
            throw new Exception("put的字符串为null");
        }
        char[] arr = str.toCharArray();
        strcat(arr, str.length(), len);
    }

    private void strcat(char[] arr, int strLen, int startIndex) {
        if (strLen > free) {
            addLen(strLen);
        }
        for (int i = 0; i < strLen; i++) {
            buf[startIndex + i] = arr[i];
        }
        len = len + strLen;
        free = buf.length - len;
        buf[len] = '\0';
    }

    private void addLen(int strlen) {
        int newBufLen = buf.length;
        int needLen = len > free ? len : free;
        if (strlen >= needLen) needLen = strlen;
        if (len < 1024 * 1024 ) {
            newBufLen = 2 * needLen + 1;
        } else if (len >= 1024 * 1024) {
            newBufLen = strlen + 1024 * 1024 + 1 ;
        }
        char[] newBuf = new char[newBufLen];
        for (int i = 0 ; i < len; i++) {
            newBuf[i] = buf[i];
        }
        buf = newBuf;
    }

}
